import axios from 'axios'
import { useAuthStore } from '@/stores/auth'
import { pinia } from '@/stores'

// 统一走代理：业务侧只写 '/user/me' 这种，不要再写 /api 前缀
export const http = axios.create({ baseURL: '/api', timeout: 15000 })

http.interceptors.request.use(cfg => {
    const auth = useAuthStore(pinia)
    const t = auth.token
    const willAttach = t && t !== 'null' && t !== 'undefined'
    console.log(
        '[HTTP ->]',
        (cfg.method || 'get').toUpperCase(),
        cfg.baseURL + (cfg.url || ''),
        'attachAuth=', willAttach,
        'tokenShort=', willAttach ? (t.slice(0, 12) + '...') : '(none)'
    )
    if (willAttach) {
        cfg.headers = { ...(cfg.headers || {}), Authorization: `Bearer ${t}` }
    }
    return cfg
})

http.interceptors.response.use(
    r => { console.log('[HTTP <-]', r.status, r.config.baseURL + r.config.url); return r },
    err => {
        const r = err?.response
        console.warn('[HTTP ! ]', r?.status, r?.config?.baseURL + r?.config?.url, r?.data || err.message)
        return Promise.reject(err)
    }
)
